#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>


#define LED_MAJOR 200
#define NAME "led"

#define GPIO_BASE       0xE000A000
#define DATA_OFFSET     0x40
#define DIRM_OFFSET     0x204
#define OUTEN_OFFSET    0x208
#define INTDIS_OFFSET   0x214
#define APER_CLK_CTRL   0xF800012C


static void __iomem *data_reg;
static void __iomem *dirm_reg;
static void __iomem *outen_reg;
static void __iomem *intdis_reg;
static void __iomem *aper_clk_reg;


static int led_open(struct inode *inode, struct file *filp)
{
    printk("led open!\n");
    return 0;
}

static int led_release(struct inode *inode, struct file *filp)
{
    printk("led released!\n");
    return 0;
}

static ssize_t led_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
    return 0;
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    int ret,val;
    char kern_buf[1];
    ret=copy_from_user(kern_buf,buf,cnt);

    val=readl(data_reg);
    if(kern_buf[0]==0){
        val &=~(1<<7);
    }
    else{
        val |=1<<7;
    }
    writel(val,data_reg);

    return 0;
}

static struct file_operations led_fops={
    .owner=THIS_MODULE,
    .open=led_open,
    .read=led_read,
    .write=led_write,
    .release=led_release,
};

static int __init led_init(void)
{
    u32 val;
    int ret;

    /*1*/
    data_reg=ioremap(GPIO_BASE+DATA_OFFSET,4);
    dirm_reg=ioremap(GPIO_BASE+DIRM_OFFSET,4);
    outen_reg=ioremap(GPIO_BASE+OUTEN_OFFSET,4);   
    intdis_reg=ioremap(GPIO_BASE+INTDIS_OFFSET,4);
    aper_clk_reg=ioremap(APER_CLK_CTRL,4);  

    /*2*/
    val=readl(aper_clk_reg);
    val|=1<<22;
    writel(val,aper_clk_reg);

    /*3*/
    val=0;
    val|=1<<7;
    writel(val,intdis_reg);

    /*4*/
    val=readl(dirm_reg);
    val |=1<<7;
    writel(val,dirm_reg);

    /*5*/
    val=readl(outen_reg);
    val|=1<<7;
    writel(val,outen_reg);

    /*6*/
    val=readl(data_reg);
    val &=~(1<<7);
    writel(val,data_reg);

    /*7*/
    ret=register_chrdev(LED_MAJOR, NAME, &led_fops);
    if(ret>=0){
        printk("led init()\n");
    }

    return 0;
}

static void __exit led_exit(void)
{
    unregister_chrdev(LED_MAJOR,NAME);

    iounmap(data_reg);
    iounmap(dirm_reg);
    iounmap(outen_reg);   
    iounmap(intdis_reg);
    iounmap(aper_clk_reg);  

    printk("led_exit()\n");
}

module_init(led_init);
module_exit(led_exit);

MODULE_AUTHOR("xujianchao");
MODULE_DESCRIPTION("xujianchao ZYNQ GPIO LED Driver");
MODULE_LICENSE("GPL");